package guestbook;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Locale;

import javax.servlet.http.*;

import com.google.appengine.api.datastore.DatastoreService;
import com.google.appengine.api.datastore.Entity;
import com.google.appengine.api.datastore.FetchOptions;
import com.google.appengine.api.datastore.Query;
import com.google.appengine.api.datastore.Query.SortDirection;
import com.google.appengine.api.datastore.Text;

@SuppressWarnings("serial")
public class HRGuestBookServlet extends HttpServlet
{
	public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException
	{
		try
		{
			resp.setContentType("text/html");

			Context context = new Context(req, resp);

			DatastoreService datastore = context.getDatastoreService();

			// If there is a new message put it to the datastore.
			String message;
			if ((message = req.getParameter("message")) != null)
			{
				Entity newEntry = new Entity("Entry");
				newEntry.setProperty("Message", new Text(message));
				datastore.put(newEntry);
			}

			resp.getWriter().println("<h1>HR Guest Book</h1>");
			resp.getWriter().println("<form><textarea name=message ></textarea><input type=submit></form><hr>");

			// List existing entries
			Query getMessages = new Query("Entry");
			getMessages.addSort("DateCreated", SortDirection.DESCENDING);
			List<Entity> messages = datastore.prepare(getMessages).asList(FetchOptions.Builder.withLimit(25));

			for (Entity messageEntity : messages)
			{
				String messageTxt = ((Text) messageEntity.getProperty("Message")).getValue();

				Date today = new Date(((Number) messageEntity.getProperty("DateCreated")).longValue());
				SimpleDateFormat formatter = new SimpleDateFormat("yyyy.MM.dd 'at' hh:mm:ss aaa z", Locale.US);
				String dateCreated = formatter.format(today);
				resp.getWriter().println("<div>" + dateCreated + " " + messageTxt + "</div>");
			}

		}
		catch (Exception ex)
		{
			ex.printStackTrace(System.err);
			resp.sendError(500, ex.toString());
		}
	}
	
	public void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException
	{
		doGet(req,resp);
	}
}
